package gen.tools.email;

import gen.tools.Widgets;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UpdateEmpMail extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public UpdateEmpMail() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		Widgets wid = new Widgets();
		request.setCharacterEncoding( wid.UIcodeSet );
		response.setContentType("application/json");
		response.setCharacterEncoding( wid.UIcodeSet );
		
		String subsysId = request.getParameter("subsysId");
		int mailId = Integer.parseInt( request.getParameter("mailId") );
		String empId = request.getParameter("empId");					
		String creatorId = request.getParameter("creatorId");			//進行這次異動的當事人
		String addOrDelete = request.getParameter("addOrDelete");
		int systemId = Integer.parseInt( request.getParameter("systemId") );
		String sql = "";
		String res = "";
		
		Connection conn = null;
		PreparedStatement ps = null;
		
		try {
			conn = wid.getConn();
			
			if ( "add".equalsIgnoreCase( addOrDelete ) ) {
				sql = "INSERT INTO mpempmailsubsys (subsysId,mailId,empId,sysSN,creatorId,cDT) VALUES (?,?,?,?,?,?)";
			} else {
				sql = "DELETE FROM mpempmailsubsys WHERE subsysId=? AND mailId=? AND empId=? AND sysSN=?";
			}
			ps = conn.prepareStatement(sql);
			ps.setString(1, subsysId);
			ps.setInt(2, mailId);
			ps.setString(3, empId);
			ps.setInt(4, systemId);
			if ( "add".equalsIgnoreCase( addOrDelete ) ) {
				ps.setString(5, creatorId);
				ps.setTimestamp(6, wid.cDT());
			}
			ps.execute();
		} catch (Exception e) {
			wid.errLog(e);
			res = wid.errProcess(e);
		} finally {
			try {
				if ( ps !=null ) {ps.close();}
				if ( conn !=null ) {conn.close();}	
			} catch (Exception e) { e.printStackTrace(); };
			
		}
		response.getWriter().write(res);
	}

}
